package org.jvm.classfile.attributeinfo;

import org.jvm.classfile.ClassReader;

/**
 * 行号表属性
 *
 * @author 海燕
 * @date 2023/2/25
 */
public class LineNumberTableAttribute implements AttributeInfo {

    private LineNumberTableEntry[] lineNumberTable;

    @Override
    public void readInfo(ClassReader classReader, int attributeLength) {
        int lineNumberTableLength = classReader.readUint16();
        this.lineNumberTable = new LineNumberTableEntry[lineNumberTableLength];
        for (int i = 0; i < this.lineNumberTable.length; i++) {
            int startPc = classReader.readUint16();
            int lineNumber = classReader.readUint16();
            this.lineNumberTable[i] = new LineNumberTableEntry(startPc, lineNumber);
        }
    }

    public int getLineNumber(int pc) {
        for (int i = this.lineNumberTable.length - 1; i >= 0; i--) {
            LineNumberTableEntry entry = this.lineNumberTable[i];
            if (pc >= entry.getStartPc()) {
                return entry.getLineNumber();
            }
        }
        return -1;
    }
}
